package com.example.springboot.controller;

import com.example.springboot.mapper.DepartmentMapper;
import com.example.springboot.mapper.EmployeeMapper;
import com.example.springboot.entity.Department;
import com.example.springboot.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeMapper employeeMapper;
    //为了把这个部门显示在add页面的下拉菜单里 导入这个接口
    @Autowired
    DepartmentMapper departmentMapper;

    //查询所有员工返回列表页面
    @GetMapping("/emps")
    public String list(Model model) {
        List<Employee> employees = employeeMapper.getAll();
        //放在请求域中
        model.addAttribute("emps", employees);
        // thymeleaf默认就会拼串
        // classpath:/templates/xxxx.html
        return "emp/list";
    }

    @GetMapping("/emp")
    public String addPage(Model model) {
        List<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("depts", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println("保存的员工信息" + employee);
        employeeMapper.add(employee);
        //回到员工列表页面 用redirect 重定向到当前项目下的emps
        return "redirect:/emps";
    }
    //查出当前员工并进行页面回显
    @GetMapping("/emp/{id}")
    public String editEmp(@PathVariable("id") Integer id, Model model) {
        //@PathVariable("id") 获取页面路径的id变量值 model封装这个id的Employee 对象
        System.out.println("页面传来 获取的id:"+id);
        Employee employee = employeeMapper.get(id);//获取要查的id对象
        System.out.println("要查找的对象"+employee.toString());
        model.addAttribute("emp",employee);

        //页面显示所有部门列表
        List<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("depts", departments);
        return "emp/edit";
    }


    //员工修改；
    @PutMapping("/emp")
    public String updateEmployee(Employee employee, HttpServletRequest request){
//        System.out.println(request.getParameter("DepartmentName"));//可以获得
        employee.setDepartment(request.getParameter("DepartmentName"));
        System.out.println("修改的员工数据："+employee);
        employeeMapper.update(employee);
        return "redirect:/emps";
    }
    //员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeMapper.delete(id);
        return "redirect:/emps";
    }


}
